const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const bodyParser = require('body-parser');

const sequelize = require('./models');
const User = sequelize.models.User;

// 同步模型到数据库
sequelize.sync().then(() => {
    console.log('数据库模型已同步');
});


// 密码正则：6-20位，包含字母和数字
const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(middlewares);
server.use(jsonServer.rewriter(require('./routes.json')));

// 自定义中间件：处理注册和登录
server.use((req, res, next) => {
    if (req.method === 'POST' && req.path === '/register') {
        handleRegister(req, res);
    } else if (req.method === 'POST' && req.path === '/login') {
        handleLogin(req, res);
    } else {
        next();
    }
});

// 注册处理函数
function handleRegister (req, res) {
    const { username, password, email } = req.body;
    const db = router.db;
    const users = db.get('users').value();

    // 验证必填字段
    if (!username || !password || !email) {
        return res.status(400).json({
            code: 400,
            error: "缺少必要参数",
            details: "需要提供 username, password 和 email"
        });
    }
    User.create({
        username,
        password, // 注意：应使用加密存储
        email
    })
        .then(user => {
            res.status(201).json({
                code: 201,
                message: "注册成功",
                data: {
                    user_id: user.id,
                    username: user.username,
                    created_at: user.createdAt
                }
            });
        })
        .catch(err => {
            if (err.name === 'SequelizeUniqueConstraintError') {
                return res.status(400).json({
                    code: 400,
                    error: "用户名已存在",
                    details: {
                        invalid_field: "username",
                        suggested: `${username}_${Math.floor(Math.random() * 1000)}`
                    }
                });
            }
            console.error(err);
            res.status(500).json({ code: 500, error: "服务器内部错误" });
        });
    // 验证密码格式
    if (!PASSWORD_REGEX.test(password)) {
        return res.status(400).json({
            code: 400,
            error: "密码格式错误",
            details: "密码必须为6-20位且包含字母和数字"
        });
    }

    // 检查用户名是否已存在
    const userExists = users.some(user => user.username === username);
    if (userExists) {
        return res.status(400).json({
            code: 400,
            error: "用户名已存在",
            details: {
                invalid_field: "username",
                suggested: `${username}_${Math.floor(Math.random() * 1000)}`
            }
        });
    }

    // 创建新用户
    const newUser = {
        id: Date.now(), // 使用时间戳作为ID
        username,
        password, // 注意：实际应用中应加密存储
        email,
        role: "student",
        createdAt: new Date().toISOString()
    };

    db.get('users').push(newUser).write();

    res.status(201).json({
        code: 201,
        message: "注册成功",
        data: {
            user_id: newUser.id,
            username: newUser.username,
            created_at: newUser.createdAt
        }
    });
}

// 登录处理函数
function handleLogin (req, res) {
    const { username, password } = req.body;
    const db = router.db;
    const users = db.get('users').value();

    // 验证必填字段
    if (!username || !password) {
        return res.status(400).json({
            code: 400,
            error: "缺少必要参数",
            details: "需要提供 username 和 password"
        });
    }

    // 查找用户
    const user = users.find(u => u.username === username && u.password === password);

    if (!user) {
        return res.status(401).json({
            code: 401,
            error: "认证失败",
            details: "用户名或密码错误"
        });
    }

    // 生成模拟token（实际应用中应使用JWT）
    const token = `token_${Date.now()}_${user.id}`;

    res.json({
        code: 200,
        message: "登录成功",
        data: {
            user_info: {
                user_id: user.id,
                username: user.username,
                role: user.role
            },
            auth: {
                token: token,
                expires_in: 3600 // 1小时
            }
        }
    });
}

// 使用默认JSON Server路由
server.use(router);

// 启动服务器
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`JSON Server 正在运行于 http://localhost:${PORT}`);
    console.log(`注册接口: POST http://localhost:${PORT}/register`);
    console.log(`登录接口: POST http://localhost:${PORT}/login`);
    console.log(`用户数据: GET http://localhost:${PORT}/users`);
});